package com.base.helper;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author mzl.
 */
public class BaseController {

    /**
     * 获取字段校验不通过的信息
     *
     * @param result 绑定结果
     */
    protected Map<String, String> getErrors(final BindingResult result) {
        Map<String, String> map  = new HashMap<String, String>();
        List<FieldError>    list = result.getFieldErrors();
        for (FieldError error : list) {
            System.out.println("error.getField():" + error.getField());
            System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());

            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }

    /**
     *
     */
    protected final Result<String> error(final BindingResult result) {
        Map<String, String> map    = this.getErrors(result);
        String              errmsg = map.values().iterator().next();
        return new Result(false, "操作失败", errmsg, errmsg);
    }

}
